package GUI;

import beans.User;
import export.ExportToExcel;
import service.CustomerService;
import service.LogService;
import service.MerchantService;
import service.OrderService;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.text.DecimalFormat;

public class MerchantFrame extends JFrame implements ActionListener {
    private JFrame frame;
    private JPanel topPanel, centerPanel, infoPanel, merPanel, warPanel, orderPanel, logPanel, helpPanel;
    private JButton infoButton, merButton, warButton, orderButton, logButton, helpButton, exitButton;

    private CardLayout cardLayout;

    private String currentPanel;

    public void MerchantFrame(User merchant) {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("用户 " + merchant.getName() + " 欢迎使用莆田大亨");

        topPanel = new JPanel(new BorderLayout());
        JPanel buttonPanel = new JPanel();
        BoxLayout boxLayout = new BoxLayout(buttonPanel, BoxLayout.Y_AXIS);
        buttonPanel.setLayout(boxLayout);

        infoButton = new JButton("个人信息");
        merButton = new JButton("商品信息");
        warButton = new JButton("仓         库");
        orderButton = new JButton("订单信息");
        logButton = new JButton("日志信息");
        helpButton = new JButton("帮         助");
        exitButton = new JButton("退         出");

        infoButton.addActionListener(this);
        merButton.addActionListener(this);
        warButton.addActionListener(this);
        orderButton.addActionListener(this);
        logButton.addActionListener(this);
        helpButton.addActionListener(this);
        exitButton.addActionListener(this);

        buttonPanel.add(infoButton);
        buttonPanel.add(merButton);
        buttonPanel.add(warButton);
        buttonPanel.add(orderButton);
        buttonPanel.add(logButton);
        buttonPanel.add(helpButton);
        buttonPanel.add(exitButton);

        JPanel contentPanel = new JPanel();

        topPanel.add(buttonPanel, BorderLayout.WEST);
        topPanel.add(contentPanel, BorderLayout.CENTER);

        // 创建中间展示面板和各子面板
        centerPanel = new JPanel();
        cardLayout = new CardLayout();
        centerPanel.setLayout(cardLayout);
        infoPanel = createInfoPanel(merchant);
        merPanel = createMerPanel(merchant);
        warPanel = createWarPanel(merchant);
        orderPanel = createOrderPanel(merchant);
        logPanel = createLogPanel(merchant);
        helpPanel = createHelpPanel(merchant);
        centerPanel.add(infoPanel, "info");
        centerPanel.add(merPanel, "mer");
        centerPanel.add(warPanel,"war");
        centerPanel.add(orderPanel, "order");
        centerPanel.add(logPanel, "log");
        centerPanel.add(helpPanel, "help");
        currentPanel = "info";  // 设置初始面板为个人信息面板
        frame.getContentPane().add(topPanel, BorderLayout.WEST);
        frame.getContentPane().add(centerPanel, BorderLayout.CENTER);
        frame.setSize(1000, 600);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);

        exitButton.addActionListener(e -> {
            MerchantService ms = new MerchantService();
            ms.Logout(merchant);
            frame.dispose();
        });

    }


    //在actionPerformed方法中添加相应的逻辑
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == infoButton) {
            cardLayout.show(centerPanel, "info");
            currentPanel = "info";
        } else if (e.getSource() == merButton) {
            cardLayout.show(centerPanel, "mer");
            currentPanel = "mer";
        } else if (e.getSource() == warButton) {
            cardLayout.show(centerPanel, "war");
            currentPanel = "war";
        } else if (e.getSource() == orderButton) {
            cardLayout.show(centerPanel, "order");
            currentPanel = "order";
        } else if (e.getSource() == logButton) {
            cardLayout.show(centerPanel, "log");
            currentPanel = "log";
        } else if (e.getSource() == helpButton) {
            cardLayout.show(centerPanel, "help");
            currentPanel = "help";
        }
    }


    // 个人信息面板
    public JPanel createInfoPanel(User merchant) {
        JPanel panel = new JPanel(new GridBagLayout());

        JLabel idLabel = new JLabel("用户ID：");
        JTextField idField = new JTextField(15);
        idField.setText(String.valueOf(merchant.getId()));
        idField.setEditable(false);

        JLabel nameLabel = new JLabel("用户姓名：");
        JTextField nameField = new JTextField(15);
        nameField.setText(merchant.getName());
        nameField.setEditable(false);

        JLabel phoneLabel = new JLabel("手机号码：");
        JTextField phoneField = new JTextField(15);
        phoneField.setText(merchant.getPhone());
        phoneField.setEditable(false);

        JLabel balanceLabel = new JLabel("账户余额：");
        JTextField balanceField = new JTextField(15);
        DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");
        balanceField.setText(decimalFormat.format(merchant.getMoney()));
        balanceField.setEditable(false);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.insets = new Insets(5, 5, 5, 5);
        panel.add(idLabel, gbc);
        gbc.gridx++;
        panel.add(idField, gbc);
        gbc.gridy++;
        gbc.gridx = 0;
        panel.add(nameLabel, gbc);
        gbc.gridx++;
        panel.add(nameField, gbc);
        gbc.gridy++;
        gbc.gridx = 0;
        panel.add(phoneLabel, gbc);
        gbc.gridx++;
        panel.add(phoneField, gbc);
        gbc.gridy++;
        gbc.gridx = 0;
        panel.add(balanceLabel, gbc);
        gbc.gridx++;
        panel.add(balanceField, gbc);

        MerchantService ms = new MerchantService();

        JButton rechargeButton = new JButton("充值");
        rechargeButton.addActionListener(e -> {
            String amountStr = JOptionPane.showInputDialog(panel, "请输入充值金额：");
            if (amountStr != null) {
                double amount = Double.parseDouble(amountStr);
                ms.rechargeBalance(merchant, amount); // 调用充值方法
                merchant.setMoney(merchant.getMoney() + amount); // 更新用户对象的余额信息
                balanceField.setText(decimalFormat.format(merchant.getMoney())); // 更新面板显示
                LogService.addLogs(merchant, "商家充值：" + decimalFormat.format(amount) + "元");
            }
        });

        JButton updatePasswordButton = new JButton("修改密码");
        updatePasswordButton.addActionListener(e -> {
            JPanel passwordPanel = new JPanel();
            JPasswordField oldPasswordField = new JPasswordField(15);
            JPasswordField newPasswordField = new JPasswordField(15);
            passwordPanel.add(new JLabel("旧密码："));
            passwordPanel.add(oldPasswordField);
            passwordPanel.add(Box.createHorizontalStrut(15));
            passwordPanel.add(new JLabel("新密码："));
            passwordPanel.add(newPasswordField);

            int result = JOptionPane.showConfirmDialog(panel, passwordPanel, "修改密码",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
            if (result == JOptionPane.OK_OPTION) {
                String oldPassword = new String(oldPasswordField.getPassword());
                String newPassword = new String(newPasswordField.getPassword());
                ms.updatePassword(merchant, oldPassword, newPassword); // 调用修改密码方法
            }
        });

        gbc.gridy++;
        gbc.gridx = 0;
        panel.add(rechargeButton, gbc);
        gbc.gridx++;
        panel.add(updatePasswordButton, gbc);

        return panel;
    }


    //商品信息面板
    private JPanel createMerPanel(User merchant) {
        JPanel panel = new JPanel(new BorderLayout());
        MerchantService ms = new MerchantService();
        //创建表格
        JTable table = ms.createJTable(merchant);

        //创建修改商品价格按钮
        JButton modifyPriceButton = new JButton("修改价格");
        modifyPriceButton.addActionListener(e -> ms.performModifyPrice(table,merchant));

        //创建修改商品状态按钮
        JButton modifyStatusButton = new JButton("修改状态");
        modifyStatusButton.addActionListener(e -> ms.performModifyStatus(merchant,table));

        //创建添加商品按钮
        JButton addButton = new JButton("添加商品");
        addButton.addActionListener(e -> ms.performAddProduct(table, merchant));

        //创建补货按钮
        JButton replenishButton = new JButton("补货");
        replenishButton.addActionListener(e -> ms.performReplenishProduct(table, merchant));

        // 创建查询文本框和按钮
        JTextField searchField = new JTextField(20);
        JButton searchButton = new JButton("查询");
        searchButton.addActionListener(e -> ms.searchTable(table, searchField.getText()));

        //创建刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> {
            ms.refreshProductData(table, merchant);
            searchField.setText("");
        });

        // 创建操作面板，并添加按钮和文本框
        JPanel operationPanel = new JPanel(new FlowLayout());
        operationPanel.add(modifyPriceButton);
        operationPanel.add(modifyStatusButton);
        operationPanel.add(replenishButton);
        operationPanel.add(refreshButton);
        operationPanel.add(searchField);
        operationPanel.add(searchButton);

        // 创建表格并添加到面板
        JScrollPane scrollPane = new JScrollPane(table);
        // 将操作面板和表格面板添加到主面板
        panel.add(operationPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 执行刷新操作
        ms.refreshProductData(table, merchant);

        return panel;

    }


    //仓库信息面板
    private JPanel createWarPanel(User merchant) {
        JPanel panel = new JPanel(new BorderLayout());
        MerchantService ms = new MerchantService();
        //创建表格
        JTable table = ms.createWJTable(merchant);

        //创建补货按钮
        JButton repButton = new JButton("缺货");
        repButton.addActionListener(e -> ms.addReplenishmentService(table,merchant));

        // 创建查询文本框和按钮
        JTextField searchField = new JTextField(20);
        JButton searchButton = new JButton("查询");
        searchButton.addActionListener(e -> ms.searchWareTable(table, searchField.getText()));

        //创建刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> {
            ms.refreshWareData(table, merchant);
            searchField.setText("");
        });

        // 创建操作面板，并添加按钮和文本框
        JPanel operationPanel = new JPanel(new FlowLayout());
        operationPanel.add(repButton);
        operationPanel.add(refreshButton);
        operationPanel.add(searchField);
        operationPanel.add(searchButton);

        // 创建表格并添加到面板
        JScrollPane scrollPane = new JScrollPane(table);
        // 将操作面板和表格面板添加到主面板
        panel.add(operationPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);


        // 执行刷新操作
        ms.refreshWareData(table, merchant);

        return panel;
    }

    //订单信息
    private JPanel createOrderPanel(User merchant) {
        JPanel panel = new JPanel(new BorderLayout());
        MerchantService ms = new MerchantService();
        // 创建表格模型
        JTable table = new JTable();

        //点击订单信息自动刷新
        orderButton.addActionListener(e -> {
            ms.showOrderData(table,merchant);
        });

        // 执行刷新操作，将数据加载到表格中
        ms.showOrderData(table, merchant);

        // 创建刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> ms.showOrderData(table, merchant));

        //退货
        JButton returnButton = new JButton("退货");
        returnButton.addActionListener(e -> ms.ReturnService(table,merchant));

        //换货
        JButton replaceButton = new JButton("换货");
        replaceButton.addActionListener(e -> ms.ReplacementService(table,merchant));

        // 执行刷新操作
        ms.refreshOrderData(table, merchant);

        // 创建导出订单按钮
        JButton exportButton = new JButton("导出订单");
        exportButton.addActionListener(e -> {
            try {
                new ExportToExcel().exportMOrdersToExcel(merchant);
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            LogService.addLogs(merchant,"商家 " + merchant.getName() + " 导出了自己的订单");
        });

        // 创建操作面板，并添加按钮
        JPanel operationPanel = new JPanel(new FlowLayout());
        operationPanel.add(refreshButton);
        operationPanel.add(returnButton);
        operationPanel.add(replaceButton);
        operationPanel.add(exportButton);
        // 创建表格并添加到面板
        JScrollPane scrollPane = new JScrollPane(table);

        // 将操作面板和表格面板添加到主面板
        panel.add(operationPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }


    //日志信息
    private JPanel createLogPanel(User merchant) {
        JPanel panel = new JPanel(new BorderLayout());
        MerchantService ms = new MerchantService();

        // 创建表格模型
        JTable table = new JTable();

        // 点击日志信息自动刷新
        logButton.addActionListener(e -> {
            ms.showLogData(table, merchant);
        });

        // 执行刷新操作，将数据加载到表格中
        ms.showLogData(table, merchant);

        // 创建刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> ms.showLogData(table, merchant));
        // 执行刷新操作
        ms.refreshLogData(table,merchant);

        // 创建导出日志按钮
        JButton exportButton = new JButton("导出日志");
        exportButton.addActionListener(e -> {
            try {
                new ExportToExcel().ExportLogToExcel(merchant);
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            LogService.addLogs(merchant,"商家 " + merchant.getName() + " 导出了自己的日志");
        });

        // 创建操作面板，并添加按钮
        JPanel operationPanel = new JPanel(new FlowLayout());
        operationPanel.add(refreshButton);
        operationPanel.add(exportButton);

        // 创建表格并添加到面板
        JScrollPane scrollPane = new JScrollPane(table);

        // 将操作面板添加到主面板的北部位置
        panel.add(operationPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }



    //帮助
    private JPanel createHelpPanel(User merchant) {
        JPanel panel = new JPanel(new BorderLayout());
        JTextArea helpArea = new JTextArea();
        helpArea.setEditable(false);
        helpArea.setText("欢迎使用银行业务自助系统！\n\n"
                + "使用本系统前，请先开通ATM服务。\n"
                + "查询余额：查询当前账户余额。\n"
                + "取款：按照提示输入取款金额。\n"
                + "存款：按照提示输入存款金额，存款金额不受限制。\n"
                + "转账：按照提示输入转账金额和账户号码进行转账操作。\n"
                + "查询日志：查询系统中的交易日志。\n"
                + "退出：退出系统退出。\n"
                + "帮助：查看系统使用帮助。\n");
        panel.add(helpArea, BorderLayout.CENTER);

        JPanel bottomPanel = new JPanel(new FlowLayout());
        return panel;
    }
}
